package com.zyjc.city.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyjc.city.constant.TimeFormat;
import com.zyjc.city.entity.Area;
import com.zyjc.city.model.params.AreaPersonIn;
import com.zyjc.city.service.AreaPersonService;
import com.zyjc.city.service.AreaService;
import com.zyjc.city.util.CqcHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ckj
 * @date 2024年03月29日 17:53
 */
@Component
@Slf4j
public class DataJob {

    @Value("${third.channelCode}")
    private String channelCode;
    @Autowired
    private ThreadPoolExecutor commonThreadPoolExecutor;
    @Autowired
    private AreaService areaService;
    @Autowired
    private AreaPersonService areaPersonService;

    /**
     * 每隔1个小时刷新token
     *
     * @author ckj
     * @date 2024/3/29 17:58
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void tokenJob() {
        CqcHttpUtil.getToken();
    }


    @Scheduled(cron = "0 0/1 * * * ? ")
    public void pullData() {
        //查询可以同步区域
        LambdaQueryWrapper<Area> query = new LambdaQueryWrapper<>();
        query.eq(Area::getState, 0);
        List<Area> areas = areaService.list(query);
        for (Area area : areas) {
            commonThreadPoolExecutor.submit(() -> {
                AreaPersonIn areaPersonIn = new AreaPersonIn();
                areaPersonIn.setAreaId(area.getAreaId());
                Date endTime = new Date();
                DateTime startTime = DateUtil.offsetMinute(endTime, -10);
                areaPersonIn.setSTime(startTime);
                areaPersonIn.setETime(endTime);
                areaPersonService.getAreaPerson(areaPersonIn);
                log.info("{}同步数据{}", Instant.now(), JSON.toJSONStringWithDateFormat(areaPersonIn, TimeFormat.PATTERN_DATETIME));
            });
        }
    }
}
